package com.ruoyi.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.utils.pojo.AliOss;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Component("myFileUpLoadUtils")
public class FileUploadUtils {
    @Autowired
    private AliOss aliOss;

    public String upload(MultipartFile file){

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = aliOss.getEndpoint();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        String accessKeyId = aliOss.getAccessKeyId();
        String accessKeySecret = aliOss.getAccessKeySecret();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = aliOss.getBucketName();

        DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, defaultCredentialProvider);
        String originalFilename = file.getOriginalFilename();

        try {

            InputStream inputStream = file.getInputStream();
            UUID uuid = UUID.randomUUID();
            originalFilename = uuid+"_"+originalFilename;
            ossClient.putObject(bucketName, originalFilename, inputStream);

            String url = "https://"+bucketName+"."+endpoint+"/"+originalFilename;

            return url;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return  null;

    }
}
